#!/bin/env python
#-*- coding:utf-8 -*-
import sys , os 
import time
import socket , select 

class Config:
	def __init__( self , lip = u"0.0.0.0" , lnm = u"255.255.255.0" , \
				wip = u"0.0.0.0", wnm = u"255.255.255.0" , \
				ssid = None , channel = -1 , space = u"" ):
		self._config = {}
		self._config["lip"] = lip
		self._config["lnm"] = lnm
		self._config["wip"] = wip
		self._config["wnm"] = wnm
		self._config["ssid"] = ssid
		self._config["channel"] = channel
		self._config["space"] = space

	def cutSsid( self , Ssid = self._config["ssid"]):
		if Ssid:
			return []
		tempArray = []
		ansArray = []
		Ssid = Ssid.strip()
		tempArray = Ssid.split["_"]
		tempArray = [ x[1:]  for x in tempArray[1:]]
		return tempArray
	
	def updateSsid( self , newSsid ):
		if newSsid == "" or newSsid == self._config["ssid"]: 
			return -1
		newSsidArray = self.cutSsid( newSsid )
		nowSsidArray = self.cutSsid()
		
		if self._config["ssid"]:
			if newSsidArray[1] > nowSsidArray[1]:
				self._config["ssid"] = u"NODE_I%s_V%s_C%s"%( nowSsidArray[0] , newSsidArray[1] , nowSsidArray[2] )
		else:
			self._config["ssid"] = newSsid
		return 1

	def updateSpace( self ):
		try:
			fDfInfo = os.popen( "df" )
		except Exception , e:
			print str(e)
		tempDfInfo = fDfInfo.read().strip()
		tempArray = tempDfInfo.splitlines()
		tempArray = tempArray[1].split(" ")
		tempArray = [ x for x in tempArray if x != "" and x != " "]
		self._config["space"] = tempArray[1]


class Ap:
	def __init__( self , confPath  = "/www/conf" ):
		self._confFilePath = confPath
		self._apConf = Config()
		self._clientConf = Config()
		
	def checkConfFile( self ):
		if self._confFilePath == "":
			return -1
		if not os.path.isfile(self._confFilePath) :
			return -1
		return 1

	def getConf( self ):
		fConf = open(self._confFilePath , "r")
		tempIp = ""
		tempIp = fConf.readline().strip()
		tempIp = u"110"
		self._clientConf._config["lip"] = u"192.168.2." + unicode(int(tempIp)+1)
		self._clientConf._config["lnm"] = u"255.255.255.0"
		self._clientConf._config["wip"] = u"192.168.2." + unicode(int(tempIp)+2)
		self._clientConf._config["wnm"] = u"255.255.255.0"
		self._apConf._config["lip"] = u"192.168.2." + tempIp
		self._apConf._config["lnm"] = u"255.255.255.0"
		fConf.close()
		return 1

	def write2network( self ):
		print 1111
		if not os.path.isfile("/etc/config/network"):
			return -1
		tempStr = "\
config interface 'loopback'\n\
        option ifname   'lo'\n\
        option proto    'static'\n\
        option ipaddr   '127.0.0.1'\n\
        option netmask  '255.0.0.0'\n\
config interface 'lan'\n\
        option ifname   'eth0'\n\
        option type     'bridge'\n\
        option proto    'static'\n\
        option ipaddr   '%s'\n\
        option gateway  '192.168.2.1'\n\
        option netmask  '%s'\n"%( self._apConf._config["lip"] , self._apConf._config["lnm"] )
		print tempStr
		fNetwork = open("/etc/config/network" , "w");
		fNetwork.write(tempStr)
		fNetwork.close()
		return 1

	def write2wireless( self ):
		if not os.path.isfile("/etc/config/wireless"):
			return -1
		self._apConf._config["channel"] = 1
		self._apConf._config["ssid"] = "NODE_I"
		tempStr = "\
config wifi-device  radio0\n\
	option type     mac80211\n\
	option channel  %d\n\
	option macaddr  14:e6:e4:a6:f7:b8\n\
	option hwmode   11ng\n\
	option htmode   HT20\n\
	list ht_capab   SHORT-GI-20\n\
	list ht_capab   SHORT-GI-40\n\
	list ht_capab   RX-STBC1\n\
	list ht_capab   DSSS_CCK-40\n\
	# REMOVE THIS LINE TO ENABLE WIFI:\n\
	# option disabled  1\n\
config wifi-iface\n\
	option device   radio0\n\
	option network  lan\n\
	option mode     ap\n\
	option ssid     %s\n\
	option encryption psk\n\
	option key      hahah818\n"%( self._apConf._config["channel"] , self._apConf._config["ssid"] )
		print tempStr
		fNetwork = open("/etc/config/wireless" , "w");
		fNetwork.write(tempStr)
		fNetwork.close()
		return 1



	def socketserver( self ):
		server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		server.setblocking(False)
		server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR  , 1)
		server_address= ( self._apConf._config["lip"] , 50000)
		server.bind(server_address)
		server.listen(10)
		inputs = [server]
		outputs = []
		message_queues = {}
		timeout = 20
		flag = 0
		while 1:
			print "waiting for next event"
			readable , writable , exceptional = select.select(inputs, outputs, inputs, timeout)
			for s in readable :
				if s is server:
					connection, client_address = s.accept()
					print "    connection from ", client_address
					connection.setblocking(0)
					inputs.append(connection)
				else:
					try:
						data = s.recv(4096)
					except Exception , e:
						print str(e)
						continue
					if data :
						print " received " , data , "from ",s.getpeername()
						if data.find("SSID:") != -1:
							flag = 1
							self._apConf.updateSsid( newSsid )
						if s not in outputs:
							outputs.append(s)
			for s in writable:
				print " sending  to ", s.getpeername()
				if flag:
					tempStr = "ok" 
					flag = not flag
				else:
					tempStr = "_1_"
				try:
					s.send(tempStr)
				except Exception , e:
					print str(e)
				else:
					print "send info " , tempStr
				outputs.remove(s)
			time.sleep(1)



	def run( self ):
		while 1:
			if self.checkConfFile() != 1:
				continue
			if self.getConf() != 1:
				continue
			if self.write2network() != 1:
				continue
			if self.write2wireless() != 1:
				continue
			os.system("/etc/init.d/network restart")
			self.socketserver()
		
if __name__ == '__main__':
	cl = Ap("/www/conf/test")
	cl.run()
